package com.example.fall_guard_band.controller;

import com.example.fall_guard_band.pojo.entity.SensorData;
import com.example.fall_guard_band.service.CsvExportService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequiredArgsConstructor
public class SensorController {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final CsvExportService csvExportService;

    @PostMapping("/sensor/data")
    public ResponseEntity<String> receiveSensorData(@RequestBody SensorData sensorData) {
        try {
            // 将对象转换为格式化的JSON字符串
            String jsonString = objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(sensorData);
            
            // 打印接收到的数据统计信息
            log.info("=== 接收到传感器数据 ===");
            log.info("Frame Timestamp: {}", sensorData.getFrameTimestamp());
            log.info("加速度计数据条数: {}", sensorData.getAccelerometerList().size());
            log.info("陀螺仪数据条数: {}", sensorData.getGyroscopeList().size());
            log.info("磁力计数据条数: {}", sensorData.getMagnetometerList().size());
            
            // 打印完整的JSON数据
            log.info("完整传感器数据 (JSON格式):\n{}", jsonString);
            
            // 导出数据到CSV文件
            csvExportService.exportSensorDataToCsv(sensorData);
            
            return ResponseEntity.ok("Data received and exported successfully!");
            
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e.getMessage());
            // 降级到toString()方式
            log.info("传感器数据 (toString): {}", sensorData);
            
            // 即使JSON序列化失败，仍然尝试导出CSV
            csvExportService.exportSensorDataToCsv(sensorData);
            
            return ResponseEntity.ok("Data received and exported successfully!");
        }
    }

}


